import { createSlice,createAsyncThunk } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import { RootState } from '../../app/store';
import http from '../../api';
import { BannerItem, SaveItem, HotRes, SaveWord, Category,ThemeResult,SaveThemeList , ImgList, Tags,Select,SaveSelect, CurType} from "../../myTypes"
import { Data } from "../../api"


interface Banner { 
  bannerList: Array<SaveItem>
  hotWords: Array<SaveWord>
  tags: Array<Category>
  themeList: Array<SaveThemeList>
  themeTags: Array<Tags>
  themeImgList: Array<ImgList>
  loadMore: boolean,
  type: string
  leftSelect:Array<SaveSelect>
  rightSelect:Array<SaveSelect>
  leftAttentionList:Array<SaveSelect>
  rightAttentionList:Array<SaveSelect>
} 
  
// 保存在redux中的数据类型
const initialState: Banner = {
  bannerList: [],
  hotWords: [],
  tags: [],
  themeList: [],
  themeTags: [],
  themeImgList: [],
  loadMore: true,
  type: "猜你喜欢",
  leftSelect:[],
  rightSelect:[],
  leftAttentionList:[],
  rightAttentionList:[]
};

// 保存在redux中的热词数据类型

// 获取轮播图数据
export const saveSwiperAsync = createAsyncThunk(
  'saveSwiper',
  async () => {
    const response = await http('get', '/mty/advert/getAll');
    return response;
  }
);
// 获取首页热词数据
export const saveHotWordAsync = createAsyncThunk(
  'saveHotWord',
  async () => {
    const response = await http('get', '/mty/hotWord/getIndexHot');
    return response;
  }
);

// 获取首页四个导航的数据
export const saveIndexTagsAsync = createAsyncThunk(
  'saveIndexTagsWord',
  async () => {
    const response = await http('get', '/mty/category/getAlls');
    return response;
  }
);
// 获取首页巴南好去处数据
export const savaIndexThemeAsync = createAsyncThunk(
  'saveIndexTheme',
  async (data: Data) => {
    const response = await http('post', '/mty/theme/query', data);
    return response;
  }
);
// 获取热门去处数据
export const savaIndexSelectAsync = createAsyncThunk(
  'saveIndexSelectTheme',
  async (data: Data) => {
    const response = await http('get', '/mty/circle/getRandom', data);
    return response;
  }
);

// 获取首页我的关注数据
export const savaIndexAttentionAsync = createAsyncThunk(
  'saveIndexAttentionTheme',
  async (data: Data) => {
    const response = await http('get', '/mty/my/getAttentionCircles', data);
    return response;
  }
);

export const bannerSlice = createSlice({
  name: 'banner',
  initialState,
  reducers: {
    toggleType: ((state, action: PayloadAction<CurType>) => { 
      state.type = action.payload
    }),
    setLoadMoreToTrue: ((state, action: PayloadAction<boolean>) => { 
      state.loadMore = action.payload
    }),
    // 清空数据
    clearLeftSelect: ((state, action: PayloadAction<Array<SaveSelect>>) => { 
      state.leftSelect = action.payload
    }),
    clearRightSelect: ((state, action: PayloadAction<Array<SaveSelect>>) => { 
      state.rightSelect = action.payload
    }),
    clearLeftAttentionList: ((state, action: PayloadAction<Array<SaveSelect>>) => { 
      state.leftAttentionList = action.payload
    }),
    clearRightAttentionList: ((state, action: PayloadAction<Array<SaveSelect>>) => { 
      state.rightAttentionList = action.payload
    })
  },
  extraReducers: (builder) => {
    // 监听轮播图请求
    builder
      .addCase(saveSwiperAsync.fulfilled, (state, action:PayloadAction<any>) => {
        const data: Array<BannerItem> = action.payload.data
        const newData =  data.map(b => { 
          return {
            id: b.id,
            advertImg: b.advertImg,
            advertName: b.advertName,
            advertUrl: b.advertUrl
          }
        })
        // 将数据保存到redux中
        state.bannerList = [...newData]
      })
      // 监听首页热词请求
    builder.addCase(saveHotWordAsync.fulfilled, (state, action: PayloadAction<any>) => { 
      const data: HotRes = action.payload.data
      const words = data.list.map(w => { 
        return {
          id: w.id,
          word: w.word
        }
      }) 
      state.hotWords = [...words]
    })
    // 获取首页四个导航
    builder.addCase(saveIndexTagsAsync.fulfilled, (state, action:PayloadAction<any>) => { 
      const tags:Array<Category> = action.payload.data
      state.tags = [...tags]
    })
    // 获取首页巴南好去处数据
    builder.addCase(savaIndexThemeAsync.fulfilled, (state, action:PayloadAction<any>) => { 
      const data: ThemeResult = action.payload.data
      let tags:Array<Tags> = []
      let imgList: Array<ImgList> = []
      const newData = data.list.map(item => { 
        tags = item.tagList
        imgList = item.imgList
        return {
          id: item.id,
          img: item.img,
          name: item.name,
          distance: item.distance
        }
      })
      state.themeList = newData
      state.themeImgList = imgList
      state.themeTags = tags
      
    })
    // 获取首页热门去处数据
    builder.addCase(savaIndexSelectAsync.fulfilled, (state, action:PayloadAction<any>) => { 
      const data: Array<Select> = action.payload.data
      console.log(data);
      
      const newData = data.map(item => {
       return {
         title: item.title,
         img: item.headFigure,
         content: item.content,
         id: item.id,
         type: item.type,
         storeId: item.storeId,
         merchantId: item.merchantId,
         address: item.address,
         isVideo: item.containVideo,
         circleUser: {
           head: item.circleUser.head,
           id: item.circleUser.id,
           name: item.circleUser.name,
           storeId:item.circleUser.storeId
         }
        }
      }) 
      newData.length <= 0 && (state.loadMore = false)
      state.leftSelect = [...state.leftSelect, ...newData.slice(0, newData.length / 2)]
      state.rightSelect = [...state.rightSelect, ...newData.slice(newData.length / 2)]
    })
    // 获取首页我的关注数据
    builder.addCase(savaIndexAttentionAsync.fulfilled, (state, action:PayloadAction<any>) => { 
      const data: {
        total: number
        list: Array<Select>
      } = action.payload.data
      console.log(data);
      const newData = data.list.map(item => {
        return {
          title: item.title,
          img: item.headFigure,
          content: item.content,
          id: item.id,
          type: item.type,
          storeId: item.storeId,
          merchantId: item.merchantId,
          address: item.address,
          isVideo: item.containVideo,
          circleUser: {
            head: item.circleUser.head,
            id: item.circleUser.id,
            name: item.circleUser.name,
            storeId:item.circleUser.storeId
          }
         }
       }) 
       newData.length <= 0 && (state.loadMore = false)
      state.leftAttentionList = [...state.leftAttentionList, ...newData.slice(0, newData.length / 2)]
      state.rightAttentionList =  [...state.rightAttentionList, ...newData.slice(newData.length / 2)]
    })
  },
});

// 暴露方法
export const {toggleType,setLoadMoreToTrue,clearLeftSelect,clearRightSelect,
  clearLeftAttentionList,clearRightAttentionList } = bannerSlice.actions;

// 将数据暴露出去
export const bannerList = (state: RootState) => state.home.bannerList;
export const hotWords = (state: RootState) => state.home.hotWords
export const tags = (state: RootState) => state.home.tags
export const themeImgList = (state: RootState) => state.home.themeImgList
export const themeTags = (state: RootState) => state.home.themeTags
export const themeList = (state: RootState) => state.home.themeList
export const loadMore = (state: RootState) => state.home.loadMore
export const type = (state: RootState) => state.home.type

// 首页猜你喜欢/我的关注数据
export const leftSelect = (state: RootState) => state.home.leftSelect
export const rightSelect = (state: RootState) => state.home.rightSelect
export const rightAttentionList = (state: RootState) => state.home.rightAttentionList
export const leftAttentionList = (state: RootState) => state.home.leftAttentionList

// 暴露bannerRReducer用于在store中进行注册
export default bannerSlice.reducer;